from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import uvicorn
import threading

app = FastAPI()

# 全局变量控制返回内容
current_response = "爱因斯坦"

def listen_to_console():
    """监听控制台输入的线程函数"""
    global current_response
    while True:
        try:
            user_input = input().strip()
            if user_input == "1":
                current_response = "爱因斯坦"
                print(f"返回内容已更改为: {current_response}")
            elif user_input == "0":
                current_response = "牛顿"
                print(f"返回内容已更改为: {current_response}")
            else:
                print("输入 '1' 切换为 '爱因斯坦'，输入 '0' 切换为 '牛顿'")
        except EOFError:
            break
        except Exception as e:
            print(f"输入错误: {e}")

@app.post("/v1/completions")
async def completions(request: Request):
    try:
        data = await request.json()
    except Exception:
        data = None
    
    # 使用全局变量控制返回内容
    return JSONResponse(content={"result": current_response})

if __name__ == "__main__":
    # 启动控制台监听线程
    console_thread = threading.Thread(target=listen_to_console, daemon=True)
    console_thread.start()
    
    print("服务已启动，输入控制命令:")
    print("输入 '1' - 返回 '爱因斯坦'")
    print("输入 '0' - 返回 '牛顿'")
    
    uvicorn.run(app, host="0.0.0.0", port=8000)